<html lang="ca"> 
<head>
    <link rel="stylesheet" href="http://localhost/projecte-sintesi-dani-victor/site_media/css/usuari/usuari_login_estilos.css">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php

//$mysqli = new mysqli("localhost", "root", "root", "calendaridaw2");

/* check connection */
/*if (mysqli_connect_errno()) {
    printf("Error de conexión: %s\n", mysqli_connect_error());
    exit();
}else{
    echo "TOT CORRECTE";
}*/
if(!(isset($_SESSION))) session_start();

require("./extras/usuari.php");

$data_usuari = unserialize($_SESSION["usuari"]);
$mailOwner =  $data_usuari->getMail();
$_SESSION["usuari"] = serialize($data_usuari);
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("calendaridaw2") or die(mysql_error());
$insercions = 0;

$uploaddir = "extras/upload/";
$uploadfile = $uploaddir . basename($_FILES['uploadedfile']['name']);
//echo $_FILES['uploadedfile']['tmp_name'] ;
$ruta  = "extras/upload/". $_FILES['uploadedfile']['name'];
echo '<pre>';
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $uploadfile))  echo "Arxiu pujat satisfactoriament.\n";
else echo "Error al subir el archivo!\n";

//echo 'Debugging Info:';
//print_r($_FILES);

// Si ja hem pujat el fitxer ara el lleguim
//echo $ruta;
$handle = fopen($ruta, "rb");
$contents = '';
while (!feof($handle)) {
  //$contents .= fread($handle, 8192);
  $contents .= fgets($handle). ":";
}
fclose($handle);
//borrem el fitxer
unlink($ruta);
/*en $contents esta el contingut a parsejar.*/
//variables array amb peces de string == fitxer
$contingut = explode(":", $contents);
//llargada del fitxer
$max = sizeof($contingut);
//paraules claus
$BEGIN = "BEGIN";
$BEGINCLASS = "Begin class";
$END = "END";
$XWRCALNAME = "X-WR-CALNAME";
$DTSTART = "DTSTART";
$DTEND = "DTEND";
$categoria = "Privat";
$SUMMARY = "SUMMARY";
$DESCRIPTION = "DESCRIPTION";        
for($i = 0; $i < $max;$i++){
      if((strcmp($contingut[$i], $XWRCALNAME)== 0)){
                $mailCalendari = trim($contingut[$i + 1]);
                $i++;
      }
}

if($mailOwner == $mailCalendari) {
    $bandera = false;
    for($i = 0; $i < $max;$i++){
        $motiu = ""; $titol= "";  $datainici= "";  $horafi= "";$motiu = "";       
         //echo  ">>>>>>>>>>>>>>>>>>>>>>>>>>>Capcelera no mola general $mailCalendari <br>".$contingut[$i];
        if((strcmp($contingut[$i], $BEGIN)== 0) && $bandera == true){
            // echo "<br>Inici eventt >>>>>>>>>>>>>>>>>>>>>>>>>>><br>";                  
           do {
               if(strcmp($contingut[$i], $DTSTART)== 0) $datainici = $contingut[$i + 1];
               if(strcmp($contingut[$i], $DTEND)== 0) $horafi = $contingut[$i + 1];
               if(strcmp($contingut[$i], $SUMMARY)== 0) $titol = $contingut[$i + 1];
               if(strcmp($contingut[$i], $DESCRIPTION)== 0) $motiu = $contingut[$i + 1];
               
               if(strcmp($contingut[$i  + 1], $END)== 0) {
                    if(strcasecmp(trim($titol), trim($BEGINCLASS)) == 0) {
                        //echo "NO INSERT INTO event es una Begin class";
                    }
                    else {
                        //tractem $data inici, $datafi per crear tres variables $datainici, $datafi, horainici
                        //$DTSTART:20130101T000000Z
                        //$DTEND:20130101T010000Z
                        $horainici = "00:00:00";
                        $horafinal = "00:00:00";
                        $datainiciParsed = "2013/01/01";
                        $datainiciParsed = parseDataInici($datainici);
                        $horainici = parseHora($datainici);
                        $horafinal = parseHora($horafi);
                        //'".$this->getMail()."', '".$this->getMotiu()."',
                        // '".$this->getTitol()."', '".$this->getCategoria()."', '".$this->getDataInici()."', '".$this->getHoraInici()."', '".$this->getHoraFi()."')

                       $insert = mysql_query( "INSERT INTO event(mail, motiu, titol, categoria, datainici, horainici, horafi) VALUES('".$mailCalendari."','".$motiu."' ,'".$titol."','".$categoria."','".$datainiciParsed."','".$horainici."','".$horafinal."');");
                       $insercions++;

                        if (!$insert) die('Consulta no válida: ' . mysql_error());

                       // echo $insert;
                    }
                    $i++;

                   break;
                }

                //echo $contingut[$i]. "<br>";
                $i++;

            } while(strcasecmp($contingut[$i], $END) != 0);
             //echo "<br>fi event  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>";
        }
        
        if((strcmp($contingut[$i], $BEGIN)== 0)) $bandera = true;
    }
    echo "S'han realitzat ".$insercions." insercions d'events.";
   
    ?> 
    <br>
    Hauras de sortir de la sessio per veure els canvis
    <a href="http://localhost/projecte-sintesi-dani-victor/index.php?calendari&action=LOGOUT_CALENDARI">SURT</a>
    
<?php
    print "</pre>";
}
else { ?>

    Aquest calendari no correspon al teu mail
    <form action='http://localhost/projecte-sintesi-dani-victor/index.php?usuari&action=EDIT_USUARI'>
   <input type=submit value=Torna>
   </form>
    

<?php }

$mysqli->close();            
            
function parseDataInici($datainici){
    $genreArray=array();
    $cadena = str_split($datainici);
    
    for($i = 0,$j = 0;$i<=7;$i++){
        $genreArray[$j] = $cadena[$i];
        $j++;
        if($i == 3 || $i == 5 ){
            $genreArray[$j] = "/";
            $j++;
        }
        
    }
    
    return implode($genreArray);
    
}   

function parseHora($datainici){
    $genreArray=array();
    $cadena = str_split($datainici);
    
    for($i = 9,$j = 0;$i <= 14;$i++){
        $genreArray[$j] = $cadena[$i];
        $j++;
        if($i == 10 || $i == 12 ){
            $genreArray[$j] = ":";
            $j++;
        }
        
        
    }
    
    return implode($genreArray);
}  

?>
</body>